<template>
  <div class="InboundList-box">
    <!-- 学期设置 -->
    <h3 class="mb16">学期设置</h3>
    <!-- 增删改查 -->
        <div class="function-box" v-if="checkPermi(['system:inventory:edit'])">
                <el-button class="addBtn2" @click="handleAdd">新增</el-button>
                <el-button class="delBtn2" @click="dels">删除</el-button>
        </div>
    <!-- 学期设置列表页面 -->
    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <!-- 添加多选列 -->
  <el-table-column 
    type="selection" 
    width="55" 
    align="center"
  />
      <el-table-column label="学年"  align="center" prop="schoolYear" :show-overflow-tooltip="true"/>
      <el-table-column label="学期" align="center" prop="termName"/>
      <el-table-column label="学期时间段" sortable align="center">
         <template #default="scope">
             <span>{{ scope.row.startDate.slice(0, 16) }}</span>至
             <span>{{ scope.row.endDate.slice(0, 16) }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="200">
        <template #default="scope">
          <el-button link class="putBtn" @click="handleClick(scope.row)">
            编辑
          </el-button>
          <el-button link class="delBtn" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="pageNum" v-model:limit="pageSize"
      @update:page="updatePage" @update:limit="updateLimit" :pageSizes="pageSizes" @pagination="handleChange" />

      <!-- 添加或修改用户配置对话框 -->
      <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
         <el-form :model="form" :rules="rules" label-position="top" ref="userRef" label-width="80px">
            <div class="formItembox">
                  <el-form-item class="formItem" label="学年" prop="schoolYear">
                     <el-input v-model="form.schoolYear" placeholder="请输入所属学年" maxlength="11" />
                  </el-form-item>
                  <!-- 日期选框 -->
                   <el-form-item class="formItem" label="学期时间段" prop="dateTime">
                    <el-date-picker
                     v-model="form.dateTime"
                     :default-time="defaultTime"
                     date-format="YYYY/MM/DD HH:mm:ss"
                     end-placeholder="结束"
                     format="YYYY-MM-DD"
                     start-placeholder="开始"
                     time-format="HH:mm"
                     type="datetimerange"
                     value-format="YYYY-MM-DD HH:mm:ss"
                     @change="handleDateChange"
                   />
                   </el-form-item>
                  <el-form-item class="formItem" label="学期" prop="termName">
                     <el-select v-model="form.termName" placeholder="请选择学期">
                        <el-option label="上学期" value="上学期"></el-option>
                        <el-option label="下学期" value="下学期"></el-option>
                     </el-select>
                  </el-form-item>
                 
                  <el-form-item class="formItem" label="备注">
                     <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                  </el-form-item>
            </div>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancel">{{ editId===-1? '重置' : '取消' }}</el-button>
               <el-button type="primary" @click="submitForm">提交</el-button>
            </div>
         </template>
      </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import pagination from '@/components/Pagination/index'
import { checkPermi } from '@/utils/permission.js'
import {listUser,addUser,delUser,detailUser,putUser} from '@/api/semester/semesterSet.js'
import dayjs from 'dayjs';


const router = useRouter();
const route = useRoute();
const data = reactive({});
const { proxy } = getCurrentInstance();

const loading = ref(false)
const treeRef = ref(null);

const title = ref("");
const open = ref(false);

const form = ref({
    dateTime:'',      //学期时间段
    schoolYear:"",    //学年
    termName:"",      //学期
    remark:"",         //备注
    startDate:"",
    endDate:"",
    
  })
/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined, 
    deptId: undefined,
    nickName: undefined, //用户昵称
    password: undefined,
    userName: undefined,
    remark: undefined,
    roleIds: [],
    // idCardPhoto:undefined,
    postIds:[1]
  };
  proxy.resetForm("userRef");
};
// const rules = ref({
//     userName: [{ required: true, message: "请输入正确的工号", trigger: "blur" }],
//     password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }, { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }],
//     roleIds: [{ required: true, message: "请选择角色", trigger: "change"}],
//     deptId: [{ required: true, message: "请选择所属组织", trigger: "change"}],
//   })

const pageSizes = ref([10, 20, 30, 50])
// 总条目数   pageSize 加 1
let total = ref(0)
// 当前页数
let pageNum = ref(1)
// 条数
let pageSize = ref(50)

// 当前页面位置发生变化
const updatePage = (val) => {
  console.log(val, '第几页');
  pageNum.value = val
  listNoticeFn()
}
// 条目个数发生变化
const updateLimit = (val) => {
  console.log(val, '每页多少条');
  pageSize.value = val
  listNoticeFn()
}
// 分页器大小  当前分页器
const handleChange = (page, pageSize) => {
    console.log(page,pageSize,'打印page,pageSize');
    
}

let ids = ref([])
let piliangIds = ref('')
const handleSelectionChange = (v)=>{
    ids.value = v.map(item => item.termId);  //过滤id
    piliangIds.value = ids.value.join(',')
    console.log(piliangIds.value,'多选数据');
}
//批量删除
const dels = ()=>{
  if(ids.value.length===0){
      ElMessage({
                 message: '请先选择要删除的数据',
                 type: 'error',
               })
       return false
  }
   delUser(piliangIds.value).then(res=>{
       if(res.code===200){
           ElMessage({
                 message: '删除成功',
                 type: 'success',
               })
               listUserFn()
       }
   })
}


// 表格数据内容
let dataList = ref([])

const handleDateChange = (val) => {
  console.log('选择的时间范围:', val);
  // val 是一个数组，格式如: ["2023-11-01 00:00:00", "2023-11-30 23:59:59"]
};
/** 取消按钮 */
function cancel() {
  
};

const editId = ref(-1)
/** 新增按钮操作 */
function handleAdd() {
  title.value = '新增学期'
  editId.value = -1
  open.value = true
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      form.value.startDate = form.value.dateTime[0].slice(0,10)
      form.value.endDate = form.value.dateTime[1].slice(0,10) 
      if(editId===-1){
          addUser(form.value).then(res=>{
          if(res.code===200){
               ElMessage({
                 message: '添加成功',
                 type: 'success',
               })
               open.value = false
               listUserFn()
          }   
        })
      }else{
          putUser(form.value).then(res=>{
               if(res.code===200){
                   ElMessage({
                 message: '编辑成功',
                 type: 'success',
               })
               open.value = false
               listUserFn()
               }
          })
      } 
        
    }
  });
};
/** 修改按钮操作 */
function handleClick(row) {
  title.value = "编辑学期";
  open.value = true
  editId.value = row.termId
  detailUser(row.termId).then(res=>{
       console.log(res,'编辑详情');
       if(res.code===200){
          form.value.remark = res.data.remark
          form.value.schoolYear = res.data.schoolYear
          form.value.termName = res.data.termName
          form.value.dateTime = [
            dayjs(res.data.startDate).format('YYYY-MM-DD HH:mm:ss'),
            dayjs(res.data.endDate).format('YYYY-MM-DD HH:mm:ss')
          ];
          form.value.termId = Number(res.data.termId)
       }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
    ElMessageBox.confirm(
    '确定要删除该数据吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
         delUser(row.termId).then(res=>{
            if(res.code===200){
                ElMessage({
                 message: '删除成功',
                 type: 'success',
               })
               listUserFn()
            }
         })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

const listUserFn = (data='')=>{  //获取列表数据
  let page = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }
  let params = Object.assign(page,data)
  // delete params.releaseDate
    listUser(params).then(res=>{
       console.log(res,'列表数据');
       if(res.code===200){
            dataList.value = res.rows
            total.value = res.total
       }
    })
}

onMounted(() => {
  Promise.all([listUserFn()])
})
// 获取发布范围下拉信息
// const genderOptions = ref([])
// const getdeptApiFn = async () => {
//   let page = {
//      pageNum: 1,
//      pageSize:-1,
//   }
//   let res = await getdeptApi(page)
//   console.log(res,'打印发布范围');
//   if (res.code == 200) {
//      genderOptions.value = res.data
//   }
// }
</script>

<style lang='scss' scoped>
.InboundList-box {
  padding: 16px;

  .function-box {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }
}
/* 最后一个 el-form-item 的 margin-left 为 0 */
:deep(.el-form-item:last-child) {
  margin-right: 0;
}
.boss{
   display: flex;
   justify-content: space-between;
}
.dialog-footer {
  display: flex;
  justify-content: center; /* 水平居中 */
}
.formItembox {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      box-sizing: border-box;

      .formItem {
        width: 28%;
        // display: flex;
        margin-right: 30px;
      }
      .formItem:last-child {
        width: 100%;
        margin-right:0;
      }
      .formItem:nth-child(3) {
        margin-right:0;
      }
    }
:deep(.el-select .el-input__wrapper) {
  width: 269px;
}
:deep(.el-textarea__inner){
    height: 80px;
}
</style>
